package com.meisiabc.support.sms;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class SmsClient {
    private static final String SMS_SERVER_URL = "http://106.ihuyi.com/webservice/sms.php?method=Submit";
    private RestTemplate restTemplate;

    public SmsClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public boolean sendSms(String mobile, String msg) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("account", "C04600536");
            map.add("password", "01d357f88e802a8ba59e73dd90ad6097");
            map.add("mobile", mobile);
            map.add("content", msg);

            ResponseEntity<String> response = restTemplate.postForEntity(SMS_SERVER_URL, new HttpEntity<>(map, headers), String.class);

            if (!(response.getStatusCode() == HttpStatus.OK)) {
                log.error("http request fail for sms.mobile: {} msg: {} statusCode:{}", mobile, msg, response.getStatusCodeValue());
                return false;
            }

            if (!response.getBody().contains("提交成功")) {
                log.error("sms server error.mobile: {} msg: {} response:{}", mobile, msg, response.getBody());
                return false;
            }

            log.info("sms success.mobile: {} msg: {} ", mobile, msg);
            return true;
        } catch (Exception e) {
            log.error("SmsClient send sms exception.", e);
        }

        return false;
    }
}
